# -*- coding: UTF-8 -*-
"""
Course:        CS408 Computer Science Project B, TEAM 1
Semester:      2010 SPRING
Project:       DOHN(Web-based Account Book System)

File:          db.py
Description:   Database Methods
Class:         None

Author:        SungHyuk Im
"""


import MySQLdb


mysql_host = "localhost"
mysql_user = "root"
mysql_password = "apmsetup"
mysql_db = "dohn"


def __get_connection__():
    """
    @author: SungHyuk Im
    @summary: Create a connection to the database and returns it.
    @return: MySQL connection object
    """
    conn = MySQLdb.connect(host = mysql_host, user = mysql_user, \
                           passwd = mysql_password, db = mysql_db)
    return conn

def run_query(sql):
    """
    @author: SungHyuk Im
    @summary: Run given query and return the result as a set of tuples.
    @param sql: SQL query
    @return: Fetched result
    """
    # Get connection and cursor
    conn = __get_connection__()
    cursor = conn.cursor()
    
    # Run the query and retrieve all rows
    cursor.execute(sql)
    result = cursor.fetchall()
    
    # Close the cursor and connection
    cursor.close()
    conn.close()
    return result
    
def execute_query(sql):
    """
    @author: SungHyuk Im
    @summary: Run the query given.
    @param sql: SQL query 
    """
    # Get connected and cursor
    conn = __get_connection__()
    cursor = conn.cursor()
    
    # Run the query and commit it
    cursor.execute(sql)
    conn.commit()
    
    # Close the cursor and connection
    cursor.close()
    conn.close()

def execute_querys(sql):
    """
    @author: Sangyong Gil
    @summary: Run the query list given.
    @param sql: SQL query list
    """
        # Get connected and cursor
    conn = __get_connection__()
    cursor = conn.cursor()
    
    # Run the query and commit it
    for aquery in sql:
        cursor.execute(aquery)
        conn.commit()
    
    # Close the cursor and connection
    cursor.close()
    conn.close()